﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Super.Hmi.Assets.CustomControl
{
    /// <summary>
    /// SelectGravatar.xaml 的交互逻辑
    /// </summary>
    public partial class SelectAvatarControl : UserControl, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        public SelectAvatarControl()
        {
            InitializeComponent();
        }

        public string GravatarImage
        {
            get { return (string)GetValue(GravatarImageProperty); }
            set { SetValue(GravatarImageProperty, value); }
        }

        public static readonly DependencyProperty GravatarImageProperty =
            DependencyProperty.Register("GravatarImage", typeof(string), typeof(SelectAvatarControl), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnGravaterChanged)));

        private static void OnGravaterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            SelectAvatarControl control = d as SelectAvatarControl;
            if (control != null)
            {
                control.IsShowGravatarImage = !string.IsNullOrEmpty(e.NewValue as string);
                control.GetBindingExpression(GravatarImageProperty)?.UpdateSource();
            }
        }

        private bool _isShowGravatarImage = false;
        public bool IsShowGravatarImage
        {
            get { return _isShowGravatarImage; }
            set
            {
                _isShowGravatarImage = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsShowGravatarImage)));
            }
        }

        private void ButtonGravatar_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif|所有文件|*.*",
                Title = "选择图片"
            };
            // 显示对话框并检查结果
            if (openFileDialog.ShowDialog() == true)
            {
                SetCurrentValue(GravatarImageProperty, openFileDialog.FileName);
            }
        }

        private void ButtonDeleteImage_Click(object sender, RoutedEventArgs e)
        {
            SetCurrentValue(GravatarImageProperty, "");
        }
    }
}
